#include "bsp_lcd.h"
#include "bsp_config.h"
#include "esp_lcd_panel_vendor.h"
#include "esp_lcd_panel_ops.h"
#include "driver/gpio.h"

static esp_lcd_panel_io_handle_t io_handle = NULL;
static esp_lcd_panel_handle_t panel_handle = NULL;

void bsp_lcd_init()
{
#ifdef BSP_DISPLAY_ENABLE
    // 初始化背光pwm
    gpio_config_t bk_gpio_config = {
        .mode = GPIO_MODE_OUTPUT,
        .pin_bit_mask = 1ULL << BSP_DISPLAY_BG_PIN,
    };
    ESP_ERROR_CHECK(gpio_config(&bk_gpio_config));

    // 添加屏幕外设
    esp_lcd_panel_io_spi_config_t io_config = {
        .dc_gpio_num = BSP_DISPLAY_ST7789_DC_PIN,
        .cs_gpio_num = BSP_DISPLAY_ST7789_CS_PIN,
        .pclk_hz = SPI_MASTER_FREQ_40M,
        .lcd_cmd_bits = 8,
        .lcd_param_bits = 8,
        .spi_mode = 0,
        .trans_queue_depth = 10,
    };
    ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)BSP_DISPLAY_ST7789_SPI_PORT, &io_config, &io_handle));
    esp_lcd_panel_dev_config_t panel_config = {
        .reset_gpio_num = BSP_DISPLAY_ST7789_RST_PIN,
        .rgb_ele_order = LCD_RGB_ELEMENT_ORDER_RGB,
        .bits_per_pixel = 16,
    };
    ESP_ERROR_CHECK(esp_lcd_new_panel_st7789(io_handle, &panel_config, &panel_handle));

    // 初始化屏幕
    ESP_ERROR_CHECK(esp_lcd_panel_reset(panel_handle));
    ESP_ERROR_CHECK(esp_lcd_panel_init(panel_handle));
    ESP_ERROR_CHECK(esp_lcd_panel_swap_xy(panel_handle, true));
#endif
}

esp_lcd_panel_handle_t bsp_lcd_get_handle()
{
    return panel_handle;
}

esp_lcd_panel_io_handle_t bsp_lcd_get_io_handle()
{
    return io_handle;
}
